package cn.readjava.controller.pay.alipay;

import cn.readjava.bean.User;
import cn.readjava.bean.UserOrder;
import cn.readjava.bean.VideoCategory;
import cn.readjava.config.AlipayProperties;
import cn.readjava.service.UserOrderService;
import cn.readjava.service.VideoCategoryService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.UUID;

/**
 * 电脑网站支付
 */
@Controller
@RequestMapping("/alipay/page")
public class AlipayPagePayController {

    @Autowired
    private AlipayProperties alipayProperties;

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private AlipayController alipayController;

    @Resource
    private VideoCategoryService videoCategoryService;

    @Resource
    private UserOrderService userOrderService;

    private String id = null;
    private String content = null;

    @RequestMapping("/gotoPayPage")
    public void gotoPayPage(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException, IOException {
        String videoId = request.getParameter("videoId");
        id = videoId;
        VideoCategory video = videoCategoryService.getOne(Long.valueOf(videoId));
        content = video.getVcTitle();
        // 订单模型
        String productCode = "FAST_INSTANT_TRADE_PAY";
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        model.setOutTradeNo(UUID.randomUUID().toString());
        model.setSubject("ReadJava教程：" + video.getVcTitle());
        model.setTotalAmount("" + video.getVcPrice());
        model.setProductCode(productCode);

        AlipayTradePagePayRequest pagePayRequest = new AlipayTradePagePayRequest();
        pagePayRequest.setReturnUrl(alipayProperties.getReturnUrl());
        pagePayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());
        pagePayRequest.setBizModel(model);

        // 调用SDK生成表单, 并直接将完整的表单html输出到页面
        String form = alipayClient.pageExecute(pagePayRequest).getBody();
        response.setContentType("text/html;charset=" + alipayProperties.getCharset());
        response.getWriter().write(form);
        response.getWriter().flush();
        response.getWriter().close();
    }

    @RequestMapping("/returnUrl")
    public String returnUrl(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, AlipayApiException {
        response.setContentType("text/html;charset=" + alipayProperties.getCharset());

        boolean verifyResult = alipayController.rsaCheckV1(request);
        if (verifyResult) {
            // 验证成功
            //订单号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            System.out.println("订单号:\t" + trade_no);
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            System.out.println("商户订单号:\t" + out_trade_no);
            // 总金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
            System.out.println("总金额:\t" + total_amount);
            // 时间
            String timestamp = new String(request.getParameter("timestamp").getBytes("ISO-8859-1"), "UTF-8");
            System.out.println("时间:\t" + timestamp);

            Subject subject = SecurityUtils.getSubject();
            User principal = (User) subject.getPrincipal();
            UserOrder userOrder = new UserOrder();

            // 保存订单
            userOrder.setOrderUserId(principal.getUserId());
            userOrder.setOrderVcId(Long.valueOf(id));
            userOrder.setOrderNo(trade_no);
            userOrder.setOrderOutNo(out_trade_no);
            userOrder.setOrderPrice(total_amount);
            userOrder.setOrderTime(timestamp);
            userOrder.setOrderContent(content);
            UserOrder result = userOrderService.save(userOrder);
            if (result == null) {
                System.out.println("********************* 订单保存失败");
            }

            return "redirect:/user/video/detail/" + id;

        } else {

            return "redirect:/user/video/index";
        }
    }
}

/*
http://localhost:8080/alipay/page/returnUrl?charset=UTF-8

订单号
&trade_no=2019021422001454760502566230
商家订单号
&out_trade_no=RJ0af5da23-8570-45bf-aa48-a00f958ec300
总金额
&total_amount=9.90
收款支付宝账号对应的支付宝唯一用户号。以2088开头的纯16位数字
&seller_id=2088102176654666
时间
&timestamp=2019-02-14+17%3A15%3A27

签名
&method=alipay.trade.page.pay.return
&sign=InwRJiE9JQcV6JDP%2F5s8T6ELWhhj37cw6MPNC8EVT55e%2BdN8S7q3ab2Hc5AKkUup0HovQBDyvLGEde3TDvBerd965VyFECKBmSXaS2Z%2FN%2Bgo4fIYqvcPJaENbybfLn%2BVrWDUblaK2NX9nuJNizua08JRZfY%2FtqkDDbchj1H5VaBC1qCma%2F6CZtkv603UKRm3mEOh6xFMjN6coJwn7e53csA%2BhGLeJR3pOjHXOwTsn1mRE5SZQEEJ8yA3o%2BJijas55nhbd92qa8VlzU%2FDz91Q62HhYJ%2BzxlpWkXxCIbWNLaA3zjO17WtQV7fgh3ojATBgFCQmtpHoROPWZwtna9FatA%3D%3D
沙箱数据
&auth_app_id=2016092100564408
&version=1.0
&app_id=2016092100564408
&sign_type=RSA2

*/
